package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class UrlFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String path = request.getServletPath();//当前的访问路径

        System.out.println(request.getServletPath());
        if (path.equals("/login.html")) {//登录不需要拦截
            filterChain.doFilter(request, servletResponse);
            return;
        }
        HttpSession session = request.getSession();
        List<String> menus = (List<String>) session.getAttribute("menus");
        for (String menu : menus) {
            if (menu.contains(path)) {//有权限就放行
                filterChain.doFilter(request, servletResponse);
                return;
            }
        }
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.sendRedirect("/error.jsp");
    }

    @Override
    public void destroy() {

    }
}
